<!--
 * @Description: 对账单列表
 * @Author: wning
 * @Date: 2023-03-25 09:36:25
 * @LastEditors: wning
 * @LastEditTime: 2023-03-30 18:50:21
-->

<template>
  <x-page class="stateAccount">
    <x-filter @search="handleSearch" @reset="handleReset">
      <x-filter-item :label="$t('financialSynergy.statement.account')">
        <el-input v-model="searchParams.number" :placeholder="'请输入'" clearable maxlength="50"></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('financialSynergy.statement.supplier')">
        <el-input v-model="searchParams.supplierName" :placeholder="'请输入'" clearable maxlength="50"></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('financialSynergy.statement.state')">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.state"
          :options="dictOptions['srm_bill.state']"
          style="width: 100%"
        ></x-select>
      </x-filter-item>
      <x-filter-item :label="$t('financialSynergy.statement.time')">
        <el-date-picker
          v-model="searchParams.time"
          type="daterange"
          value-format="yyyy-MM-dd"
          :range-separator="$t('common.to')"
          :start-placeholder="'开始时间'"
          :end-placeholder="'结束时间'"
          clearable
        >
        </el-date-picker>
      </x-filter-item>
    </x-filter>
    <x-data>
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button type="primary" v-hasPermi="['srm:bill:add']" :icon="buttonIcons('add')" @click="handleAdd">
              {{ $t('common.add') }}</el-button
            >

            <el-button
              type="primary"
              v-hasPermi="['srm:bill:send']"
              :icon="buttonIcons('send')"
              @click="handleBtn('send')"
            >
              {{ $t('common.send') }}</el-button
            >

            <el-button
              type="danger"
              v-hasPermi="['srm:bill:delete']"
              :icon="buttonIcons('delete')"
              @click="handleBtn('delete')"
            >
              {{ $t('common.batchDelete') }}</el-button
            >
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <span v-if="item.prop === 'state'">{{
              selectDictLabel(dictOptions['srm_bill.state'], scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'invoiceState'">{{
              scope.row.invoiceState == 1 ? '已开票' : '未开票'
            }}</span>
            <span v-else-if="item.prop === 'beginDate' || item.prop === 'endDate'">
              {{ replaceDateTime(scope.row[item.prop]) }}
            </span>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :align="'center'" width="160">
          <template #default="scope">
            <more-table-actions
              :permis-list="permissionsActions"
              :action-list="getActions(actions, scope.row)"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
  </x-page>
</template>

<script>
  import {
    buttonIcons,
    replaceDateTime,
    PermissionsMixin,
    QueryDictMixin,
    TableListMixin,
    selectDictLabel
  } from '@package/utils'
  import { mapState } from 'pinia'
  import { columns, actions, invoiceStateOptions } from '@/modules/financialSynergy/config/statementAccount.js'
  import {
    listUrl,
    apiBillCancle,
    apiBillDelete,
    apiBillSend
  } from '@/modules/financialSynergy/api/statementAccount.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import { pinias } from '@/common/pinia'

  const { login } = pinias
  export default {
    name: 'StatementAccount',
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        columns,
        actions,
        listUrl,
        invoiceStateOptions,
        searchParams: {
          number: '',
          state: '',
          supplierName: '',
          time: ''
        },
        tableData: [],
        srmDictKeys: ['srm_bill.state'],
        selectData: []
      }
    },
    watch: {
      dictOptions: {
        handler(val) {
          console.log('val123', val)
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      ...mapState(login, ['user']),
      getActions() {
        return (actions, row) => {
          const { state } = row
          return actions.map((action) => {
            const { key } = action
            switch (state) {
              case 1: // 草稿
                action.disabled = !['detail', 'edit', 'delete', 'send'].includes(key)
                break
              case 2: // 待确认
                action.disabled = !['detail', 'cancel'].includes(key)
                break
              case 3: // 已确认
                action.disabled = !['detail'].includes(key)
                break
              case 4: // 已拒绝
                action.disabled = !['detail', 'edit'].includes(key)
                break
              default:
                action.disabled = !['detail'].includes(key)
                break
            }
            return action
          })
        }
      }
    },
    mounted() {
      // this.loadTreeData()
    },
    methods: {
      buttonIcons,
      selectDictLabel,
      replaceDateTime,
      handleReset() {
        this.searchParams = {
          number: '',
          state: '',
          supplierName: '',
          time: ''
        }
        this.resetSearch()
      },
      handleSearch(val) {
        const { number, state, type, supplierName, time } = this.searchParams
        console.log('time: ', time)
        this.queryParam = {
          ...val,
          number,
          state,
          supplierName,
          beginTime: time ? `${time[0]} 00:00:00` : '',
          endTime: time ? `${time[1]} 23:59:59` : ''
        }
        this.loadData()
      },
      async handleActions({ key, data }) {
        const { id } = data
        switch (key) {
          case 'detail':
            this.$router.push({
              name: 'statementAccountDetail',
              query: {
                id,
                isDetail: false
              }
            })
            break
          case 'edit':
            this.$router.push({
              name: 'statementAccountEdit',
              query: {
                id,
                isDetail: false
              }
            })
            break
          case 'delete':
            this.handleDelete([id])
            break
          case 'cancel':
            this.handleCancle([id])
            break
          case 'send':
            this.handleSend([id])
            break
          default:
            break
        }
      },
      // 多行选中
      handleSelectionChange(rows) {
        this.selectData = rows
      },
      handleAdd() {
        this.$router.push({
          name: 'statementAccountAdd'
        })
      },
      handleBtn(val) {
        if (this.selectData.length === 0) {
          this.$message.error('请至少选择一条数据')
          return
        }
        const isList = this.selectData.map((item) => {
          return item.id
        })
        if (val === 'send') {
          this.handleSend(isList)
        } else if (val === 'delete') {
          this.handleDelete(isList)
        }
      },
      handleSend(parmas) {
        this.$confirm('是否确认发送选中数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiBillSend(parmas).then((res) => {
            if (res.code === EnumApiCode.Success) {
              this.$message.success(this.$t('common.opeartionSuccess'))
            } else {
              this.$message.error(res.msg)
            }
            this.loadData()
          })
        })
      },
      handleDelete(parmas) {
        this.$confirm('是否删除选中数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiBillDelete(parmas).then((res) => {
            if (res.code === EnumApiCode.Success) {
              this.$message.success(this.$t('common.deleteSuccess'))
            } else {
              this.$message.error(res.msg)
            }
            this.loadData()
          })
        })
      },
      handleCancle(id) {
        this.$confirm('是否确认取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiBillCancle(id).then((res) => {
            if (res.code === EnumApiCode.Success) {
              this.$message.success(this.$t('common.opeartionSuccess'))
            } else {
              this.$message.error(res.msg)
            }
            this.loadData()
          })
        })
      },
      handleExportExcel() {
        this.handleExport('test')
      }
    }
  }
</script>
<style scoped>
  .stateAccount >>> .el-range-editor--medium.el-input__inner {
    line-height: 32px;
    height: 32px;
    width: 100%;
  }
</style>
